package com.yaoq.observer.simple;

import java.util.ArrayList;

/**
 * @ClassName WeatherData
 * @Description 气象站实现了主题的三个抽象方法，完成对观察者的管理
 * @Author yaoqiang
 * @Date 2020/9/3 15:28
 * @Version 1.0
 */
public class WeatherData implements Subject {
    private float temperature;
    /**
     * 观察者列表
     */
    private ArrayList<Observer> observers;

    /***
     * 无参构造器，主要是初始化observers的值
     */
    public WeatherData() {
        observers = new ArrayList<Observer>();
    }

    public float getTemperature() {
        return temperature;
    }


    public void setData(float temperature) {
        this.temperature = temperature;
        //将最新的消息推送给所有的观察者
        notifyObservers();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        if (observers.contains(o)) {
            observers.remove(o);
        }
    }

    @Override
    public void notifyObservers() {
        for (int i = 0; i < observers.size(); i++) {
            observers.get(i).update(this.temperature);
        }

    }
}
